package initApp

import (
	"IrisJwtCasbin/config"
	"IrisJwtCasbin/models"
	"IrisJwtCasbin/routers"
	"IrisJwtCasbin/sysinit"
	"github.com/betacraft/yaag/yaag"
	"github.com/kataras/iris"
	irislogger "github.com/kataras/iris/middleware/logger"
)

func NewApp() *iris.Application {
	api := iris.New()
	api.Logger().SetLevel("debug")

	requestLogger := irislogger.New(irislogger.Config{
		// Status displays status code
		Status: true,
		// IP displays request's remote address
		IP: true,
		// Method displays the http method
		Method: true,
		// Path displays the request path
		Path: true,
		// Query appends the url query to the Path.
		Query: true,
		// if !empty then its contents derives from `ctx.Values().Get("logger_message")
		// will be added to the logs.
		MessageContextKeys: []string{"logger_message"},
		// if !empty then its contents derives from `ctx.GetHeader("User-Agent")
		MessageHeaderKeys: []string{"User-Agent"},
	})
	api.Use(requestLogger)
	//api.Logger().Info("test log")

	api.RegisterView(iris.HTML(config.Root+"resources", ".html"))

	db := sysinit.Db
	//数据库表同步
	db.AutoMigrate(
		&models.User{},
		&models.OauthToken{},
		&models.Role{},
		&models.Permission{},
	)

	iris.RegisterOnInterrupt(func() {
		_ = db.Close()
	})

	yaag.Init(&yaag.Config{ // <- IMPORTANT, init the middleware. //api 文档配置
		On:       true,
		DocTitle: "IrisAdminApi",
		DocPath:  config.Root + "resources/apiDoc/index.html", //设置绝对路径
		BaseUrls: map[string]string{
			"Production": config.Config.Host,
			"Staging":    "",
		},
	})

	routers.App(api) //注册 app 路由

	return api
}
